<!--历史数据-->
<template>
  <div class="ele-body">
    <!-- 搜索表单 -->
    <div class="block-interval">
      <a-card :bordered="false">
        <a-form layout="inline" :model="where">
          <a-row>
            <a-form-item label="开始时间:">
              <a-date-picker v-model:value="where.searchBeginTime" type="date" show-time format="YYYY-MM-DD HH:mm:ss" valueFormat="YYYY-MM-DD HH:mm:ss" />
            </a-form-item>
            <a-form-item label="结束时间:">
              <a-date-picker v-model:value="where.searchEndTime" type="date" show-time format="YYYY-MM-DD HH:mm:ss" valueFormat="YYYY-MM-DD HH:mm:ss" />
            </a-form-item>
            <a-form-item class="ele-text-center">
              <a-space>
                <a-button type="primary" @click="reload">查询</a-button>
                <a-button @click="reset">重置</a-button>
              </a-space>
            </a-form-item>

          </a-row>
        </a-form>
      </a-card>

      <a-card
        :bordered="false"
        title="实时统计"
        :body-style="{padding: '16px 6px 0 0'}">
        <v-chart
          ref="subMeterChart"
          style="height: 362px;"
          :option="subMeterChartOption"/>
      </a-card>
    </div>

    <!-- 表格 -->
    <div>
      <a-card :bordered="false">
        <ele-pro-table
          ref="table"
          row-key="pdwsId"
          :datasource="datasource"
          :columns="columns"
          :where="where"
          v-model:selection="selection"
          :scroll="{ x: 'max-content' }"
        >
          <template #bodyCell="{ column, record }">
            <!-- table操作栏按钮 -->
            <template v-if="column.key === 'action'">
              <a-space>
                <a-popconfirm title="确定要删除此记录吗？" @confirm="remove(record)">
                  <a class="ele-text-danger">删除</a>
                </a-popconfirm>
              </a-space>
            </template>
          </template>
        </ele-pro-table>
      </a-card>
    </div>

    <!-- 编辑弹窗 -->
  </div>
</template>

<script>
import { provide } from 'vue';
import { use } from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { LineChart, BarChart } from 'echarts/charts';
import {
  GridComponent,
  TooltipComponent,
  LegendComponent
} from 'echarts/components';
import VChart, { THEME_KEY } from 'vue-echarts';
import 'echarts-wordcloud';
import { ChartTheme } from 'ele-admin-pro';
import {DeviceWatermeterSubApi} from "@/api/property/DeviceWatermeterSubApi";
import moment from 'moment';
import { message } from 'ant-design-vue';


use([
  CanvasRenderer,
  LineChart,
  BarChart,
  GridComponent,
  TooltipComponent,
  LegendComponent
]);
provide(THEME_KEY, ChartTheme);

export default {
  name: 'DeviceWatermeterSubData',
  components: {
    VChart
  },
  props: {
    data: Object
  },
  async mounted() {
    this.getSubMeterData();
  },
  data() {
    return {
      // 表格列配置
      columns: [
        {
          title: '记录时间',
          dataIndex: 'createTime'
        },
        {
          title: '起始时间',
          dataIndex: 'lastMeterTime'
        },
        {
          title: '结束时间',
          dataIndex: 'currentMeterTime'
        },
        {
          title: '使用量(m³)',
          dataIndex: 'subPositiveflow'
        },
        {
          title: '上一次抄表的正向流量(m³)',
          dataIndex: 'lastPositiveflow'
        },
        {
          title: '当前抄表流量(m³)',
          dataIndex: 'currentPositiveflow'
        },
        {
          title: '操作',
          key: 'action',
          width: 280,
          align: 'center'
        }
      ],
      // 表格搜索条件
      where: {"recordId" : this.data.recordId},
      // 表格选中数据
      selection: [],
      // 当前编辑数据
      current: null,
      // 是否显示编辑弹窗
      showDetail: false,
      subMeterData: []
    }
  },
  computed: {
    // 最近1小时温度情况折线图配置
    subMeterChartOption() {
      return {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          },
          formatter : function (params) {
            console.log(params);
            return "起始时间:" + params[0].data?.lastMeterTime  + "<br/>"
              + "结束时间:" + params[0].data?.currentMeterTime + "<br/>"
              + "使用量:" + params[0].data?.value + "m³";
          }
        },
        axisPointer: {
          link: { xAxisIndex: 'all' },
          label: {
            backgroundColor: '#777'
          }
        },
        toolbox: {
          feature: {
            dataZoom: {
              yAxisIndex: false
            },
            brush: {
              type: ['lineX', 'clear']
            }
          }
        },
        legend: {
          data: ['使用量'],
          right: 20
        },
        xAxis: [
          {
            type: 'category',
            boundaryGap: false,
            data: this.subMeterData.map(d => d.time)
          }
        ],
        dataZoom: [
          {
            type: 'inside',
            xAxisIndex: [0, 1],
            start: 0,
            end: 100
          },
          {
            show: true,
            xAxisIndex: [0, 1],
            type: 'slider',
            top: '85%',
            start: 0,
            end: 100
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: [
          {
            name: '使用量',
            type: 'line',
            smooth: true,
            lineStyle: {
              normal: { opacity: 0.5 }
            },
            data: this.subMeterData
          }
        ]
      }
    }
  },
  methods: {
    /**
     * 搜索按钮
     *
     * @author cancan
     * @date 2022/03/05 14:48
     */
    reload() {
      this.selection = [];
      this.$refs.table.reload({ page: 1 });
      this.getSubMeterData();
    },

    /**
     * 重置搜索
     *
     * @author cancan
     * @date 2022/03/05 14:48
     */
    reset() {
      this.where.recordId = this.data.recordId;
      this.where.searchBeginTime = '';
      this.where.searchEndTime = '';
      this.$nextTick(() => {
        this.reload();
      });
    },

    /**
     * 删除
     *
     * @author cancan
     * @date 2022/03/05 14:48
     */
    async remove(row) {
      const result = await DeviceWatermeterSubApi.delete({ pdwsId: row.pdwsId });
      message.success(result.message);
      this.reload();
    },

    /**
     * 打开新增或编辑弹窗
     *
     * @author cancan
     * @date 2022/03/05 14:48
     */
    openDetail(row) {
      this.current = row;
      this.showDetail = true;
    },

    getSubMeterData(){
      let params = {
        searchBeginTime : moment().subtract(1, 'h').format('YYYY-MM-DD HH:mm:ss'),
        searchEndTime : moment().format('YYYY-MM-DD HH:mm:ss'),
        recordId : this.data.recordId,
        orderBy : "asc",
        sortBy : "current_meter_time"
      };
      if (this.where.searchBeginTime && this.where.searchEndTime) {
        params.searchBeginTime = this.where.searchBeginTime;
        params.searchEndTime = this.where.searchEndTime;
      }
      DeviceWatermeterSubApi.list(params).then(list => {
        let _subMeterData = [];
        if (list && list.length > 0) {
          list.forEach(function(item) {
            let formatItem = {
              time : item.currentMeterTime,
              value: item.subPositiveflow,
              currentMeterTime : item.currentMeterTime,
              lastMeterTime : item.lastMeterTime,
            };
            _subMeterData.push(formatItem);
          });
        } else {
          let last20 = (moment().subtract(20, 'minute')).format('YYYY-MM-DD HH:mm:ss');
          let last10 = (moment().subtract(10, 'minute')).format('YYYY-MM-DD HH:mm:ss');
          let last5 = (moment().subtract(5, 'minute')).format('YYYY-MM-DD HH:mm:ss');
          _subMeterData.push({
            time : last20,
            value : 0,
            currentMeterTime : '-',
            lastMeterTime :  '-',
          });
          _subMeterData.push({
            time : last10,
            value : 0,
            currentMeterTime : '-',
            lastMeterTime :  '-',
          });
          _subMeterData.push({
            time : last5,
            value : 0,
            currentMeterTime : '-',
            lastMeterTime :  '-',
          });
        }
        this.subMeterData = _subMeterData;
      });
    },
    /**
     * 获取表格数据
     *
     * @author fengshuonan
     * @date 2022/5/8 15:18
     */
    datasource({ page, limit, where, orders }) {
      return DeviceWatermeterSubApi.findPage({ ...where, ...orders, pageNo: page, pageSize: limit });
    },
    activated() {
      ['subMeterChart'].forEach((name) => {
        this.$refs[name].resize();
      });
    }
  }
};
</script>
